package com.xlongwei.accounts.dao;

import java.util.Collections;
import java.util.List;

import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Cache;
import org.noear.solon.data.annotation.CacheRemove;
import org.noear.solon.data.annotation.Tran;
import com.xlongwei.accounts.config.MySqlUtils;
import com.xlongwei.accounts.model.User;

@Component
public class UserDao {
    @Inject
    MySqlUtils sqlUtils;
    // User.pass序列化时不输出，因此登录时直接查数据库（不缓存）
    // @Cache(key = "user.mobile.${mobile}")
    public User findByMobile(Long mobile) {
        return sqlUtils.sql("select userid,mobile,pass,level,partner from t_user where mobile=?", mobile).queryRow(User.class);
    }

    @Cache(key = "user.partner.${mobile}")
    public List<User> findByPartner(Long mobile) {
        List<User> list = sqlUtils.sql("select userid,mobile,pass,level,partner from t_user where partner=?", mobile).queryRowList(User.class);
        return list != null ? list : Collections.emptyList();
    }

    @Cache(key = "user.${userid}")
    public User retrieve(Integer userid) {
        return sqlUtils.sql("select userid,mobile,pass,level,partner from t_user where userid=?", userid).queryRow(User.class);
    }

    @Tran
    @CacheRemove(keys = "user.${},users,user.mobile.${row.mobile}")
    public Integer create(User row) {
        assert row.getUserid() == null;
        Object key = sqlUtils
                .sql("insert into t_user(mobile,pass) values(?,?)", row.getMobile(), row.getPass())
                .updateReturnKey();
        return Integer.parseInt(key.toString());
    }

    @Tran
    @CacheRemove(keys = "user.${row.userid},users,user.mobile.${row.mobile},user.partner.${row.partner}")
    public Integer update(User row) {
        assert row.getUserid() != null;
        return sqlUtils.sql("update t_user set mobile=?,pass=?,level=?,partner=? where userid=?",
                row.getMobile(), row.getPass(), row.getLevel(), row.getPartner(), row.getUserid()).update();
    }

    @Cache(key = "users")
    public List<User> list() {
        List<User> list = sqlUtils.sql("select userid,mobile,pass,level,partner from t_user").queryRowList(User.class);
        return list != null ? list : Collections.emptyList();
    }

}
